// import { FengChangData, Header } from '@/types/index.d.ts'
import Map from 'ol/Map'
import { Windy } from "@/assets/windy.js"
import ImageLayer from 'ol/layer/Image'
import ImageCanvasSource from 'ol/source/ImageCanvas'
import { transformExtent } from 'ol/proj'
// import { Key } from 'ol/events'
// import * as d3 from 'd3'

type Windy = typeof Windy
// type FengChangData = typeof FengChangData
// type Header = typeof Header
interface WindData {
  nx: number,
  ny: number,
  data: [number, number][]
}
export default class FengChang {
  private map: Map
  private fengchangData
  private windData: WindData
  private name: String
  private data: [number, number, number, number, number][]
  private _minMag: number
  private _maxMag: number
  private windy: Windy
  private canvas: HTMLCanvasElement
  private a
  private b

  constructor(map: Map, fengchangData, name: String) {
    this.map = map
    this.fengchangData = fengchangData
    this.windData = {
      nx: 0,
      ny: 0,
      data: []
    }
    this.name = name
    this.data = []
    this._minMag = Infinity
    this._maxMag = 0
    this.canvas = document.createElement('canvas')
    this.windy = Windy({
      canvas: this.canvas,
      data: this.fengchangData
    })
    console.log(this.fengchangData)
    this.a = null
    this.b = null
    this._init()
  }
  _init() {
    // 第一步：处理数据
    let p: number = 0
    const header: Header = this.fengchangData[0]['header']
    const xdata: number[] = this.fengchangData[0]['data']
    const ydata: number[] = this.fengchangData[1]['data']
    this.windData!.nx = header.nx
    this.windData!.ny = header.ny
    for (let i = 0, j = 0; i < xdata.length, j < ydata.length; i++, j++) {
      this.windData.data.push([xdata[i], ydata[j]])
    }
    console.log(this.windData);

    for (let j = 0; j < this.windData.ny; j++) {
      for (let i = 0; i < this.windData.nx; i++, p++) {
        if (this.windData.data[p] !== undefined) {
          let vx = this.windData.data[p][0] || 0
          let vy = this.windData.data[p][1] || 0
          let mag = Math.sqrt(vx * vx + vy * vy)
          // 数据是一个一维数组
          // [ [经度, 维度，向量经度方向的值，向量维度方向的值] ]
          this.data.push([
            (i / this.windData.nx) * 360 - 180,
            (j / this.windData.ny) * 180 - 90,
            vx,
            vy,
            mag
          ])
          this._maxMag = Math.max(mag, this._maxMag)
          this._minMag = Math.min(mag, this._minMag)
        }
      }
    }

    // 第二步：添加echarts图层
    this._addFengChang()
  }
  public getWindy() {
    return this.windy
  }
  public getEventsKey() {
    return [this.a, this.b]
  }
  public getCanvas() {
    return this.canvas
  }
  _addFengChang() {
    this.canvas.style.position = 'absolute'
    this.canvas.style.top = '0'
    this.canvas.style.left = '0'
    this.canvas.style.display = 'block'
    this.map.getViewport().appendChild(this.canvas)
    // 1，这是使用windjs的方案，可以做出来效果
    this._createCanvasLayer()
    //,2，绘图登高线图，这是d3的方案，我试了不行
    // const context = this.canvas.getContext('2d')
    // var d3Path = d3.geoPath(null, context) //绘图笔
    // var contours = d3.contours()
    //   .size([this.windData.nx, this.windData.ny])
    //   .thresholds(d3.range(0, 300, 5))(this.windData.data)

    // console.log(contours);

    // contours.forEach(function (geometry: any) {
    //   context!.beginPath()
    //   d3Path(geometry)
    //   var v = geometry.value
    //   // var acolor = that.getColor(v)
    //   context!.fillStyle = 'red'
    //   context!.fill()
    //   context!.strokeStyle = 'blue'
    //   context!.stroke()
    // })
  }
  _createCanvasLayer() {
    const context = this.canvas.getContext('2d')
    const canvasSource = new ImageCanvasSource({
      canvasFunction: (extent, resolution, pixelRatio, size, projection) => {
        this.canvas.style.width = size[0] + 'px'
        this.canvas.style.height = size[1] + 'px'

        let extents = transformExtent(extent, 'EPSG:3857', 'EPSG:4326')
        this._refreshWindy(extents, size)
        return this.canvas
      }
    })
    const canvasLayer = new ImageLayer({
      opacity: 0.7,
      properties: {
        name: this.name
      }
    })

    canvasLayer.setSource(canvasSource)
    this.map.addLayer(canvasLayer)
    this.a = this.map.on('movestart', () => {
      if (context) context.clearRect(0, 0, 3000, 3000)
      this.windy.stop()
    })
    this.b = this.map.on('moveend', () => {
      let extent = this.map.getView().getViewStateAndExtent().extent
      let size = this.map.getSize()!
      this._refreshWindy(transformExtent(extent, 'EPSG:3857', 'EPSG:4326'), size)
    })
  }
  _refreshWindy(extents: number[], size: number[]) {
    const that = this
    that.canvas.style.width = size[0] + 'px'
    that.canvas.style.height = size[1] + 'px'
    that.windy.stop()
    setTimeout(function () {
      that.windy.start(
        [[0, 0], [size[0], size[1]]],
        size[0],
        size[1],
        [[extents[0], extents[1]], [extents[2], extents[3]]]
      )
    }, 500)
  }
}